package com.cxs.plan.aop;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cxs.plan.annotation.PagingQuery;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Aspect
@Component
public class PageAop {
    @Around("@annotation(pagingQuery)")
    public Object pagingQuery(ProceedingJoinPoint joinPoint, PagingQuery pagingQuery) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        System.out.println(signature);
        String pageNumParameterName = pagingQuery.pageNumParameterName();
        String pageSizeParameterName = pagingQuery.pageSizeParameterName();              //获取request，从中获取分页参数
        ServletRequestAttributes currentRequestAttributes = (ServletRequestAttributes) RequestContextHolder
                .currentRequestAttributes();
        HttpServletRequest request = currentRequestAttributes.getRequest();
        String pageNum = request.getParameter(pageNumParameterName);
        String pageSize = request.getParameter(pageSizeParameterName);
        if (StringUtils.isNotBlank(pageNum) && StringUtils.isNotBlank(pageSize)) {
            try {
                PageHelper.startPage(Integer.valueOf(pageNum), Integer.valueOf(pageSize));
                Object result = joinPoint.proceed();
                return result;

            } finally {//保证线程变量被清除
                if (PageHelper.getLocalPage() != null)
                    PageHelper.clearPage();
            }
        }
        return joinPoint.proceed();
    }
}